<template>
  <i-dialog
    title="选择区域"
    class="region-dialog"
    :visible.sync="visible"
    width="642px"
    :close-on-click-modal="false"
    @close="outerClose"
    @opened="outerOpen"
  >
    <div class="area-tree">
      <el-tree
        :data="treeData"
        :render-after-expand="false"
        :show-checkbox="showCheckbox"
        :default-expanded-keys="expanded"
        :props="defaultProps"
        ref="tree"
        :node-key="code"
        :lazy="lazy"
        :load="loadNode"
      >
      </el-tree>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="outerClose">取 消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </span>
  </i-dialog>
</template>
<script>
import _ from 'lodash'
import { getProvince, getCity, getDistrict } from '@/api/common'
export default {
  name: 'SearchTreeDialog',
  props: {
    checkedNodes: Array,
    treeInfo: Array,
    visible: {
      type: Boolean,
      required: true,
    },
    code: {
      type: String,
      default: 'id',
    },
    level: {
      type: Number,
      default: 2,
    },
    lazy: {
      type: Boolean,
      default: true,
    },
    showCheckbox: {
      type: Boolean,
      default: true,
    },
    clearable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      treeData: _.cloneDeep(this.treeInfo),
      regionOptions: [],
      checkedKeys: [],
      expanded: [],
      defaultProps: {
        label: 'name',
        isLeaf: 'leaf',
      },
      form: {
        filterInput: '',
      },
      filterCode: {},
      formItems: [
        {
          slot: 'cascader',
          span: 12,
        },
        {
          slot: 'nameInput',
          span: 12,
        },
      ],
      rules: {},
      checkedRegions: [],
    }
  },
  methods: {
    outerOpen() {
      this.checkedKeys = this.checkedNodes.map((item) => JSON.parse(item.id))
      this.$refs.tree.setCheckedKeys(this.checkedKeys || [])
    },
    outerClose() {
      this.form = {}
      this.$emit('update:visible', false)
    },
    //下拉框获取焦点
    Focus() {
      if (typeof this.selectFocus === 'function') {
        this.selectFocus()
      }
    },
    //清空
    clear() {
      this.form = []
      this.filterText = ''
      this.$refs.eltree.setCheckedKeys([])
    },
    //全选
    all() {
      if (this.isAll == false) {
        this.$refs.eltree.setCheckedNodes(this.childData)
        this.isAll = true
      } else {
        this.$refs.eltree.setCheckedKeys([])
        this.isAll = false
      }
    },
    async loadNode(node, resolve) {
      if (node.level > this.level) return resolve([])
      await this.getTreeData(node, resolve)
      this.$nextTick(() => {
        node.childNodes.forEach((item) => {
          this.checkedNodes.forEach(async (innerItem) => {
            let idPathArr = innerItem.idPath
              .split(',')
              .map((item) => JSON.parse(item))
            idPathArr.splice(-1, 1)
            if (idPathArr.includes(item.data.id)) {
              this.expanded.push(item.data.id)
            }
          })
        })
      })
    },
    async getTreeData(node, resolve) {
      const getAddressList = [getProvince, getCity, getDistrict]
      const params = node.level === 0 ? {} : { parent: node.data.id }
      let data = await getAddressList[node.level](params)
      data.forEach((item) => {
        item.leaf = node.level >= this.level
        item.idPath =
          node.level === 0 ? item.id + '' : node.data.idPath + ',' + item.id
        item.namePath =
          node.level === 0
            ? item.name + ''
            : node.data.namePath + '-' + item.name
      })
      return resolve(data)
    },
    getSimpleCheckedNodeIds(originData) {
      // 定义数组
      const checkedNodes = []
      // 判断是否为全选，若为全选状态返回被全选的节点，不为全选状态正常返回被选中的节点
      const isAllChecked = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes
        childNodes.forEach((child) => {
          if (child.checked) {
            checkedNodes.push(child.data)
          }
          if (child.indeterminate) {
            isAllChecked(child)
          }
        })
      }
      isAllChecked(originData)
      return checkedNodes
    },
    submit() {
      let list = this.getSimpleCheckedNodeIds(this.$refs.tree.store)
      this.$emit('listenCheckedInfoEvent', list)
      this.outerClose()
    },
  },
}
</script>
<style lang="scss" scoped>
.region-dialog {
  .area-tree {
    height: 450px;
    overflow: auto;
  }
}
.search-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .search-form {
    display: flex;
    &::v-deep .address-cascader {
      margin-right: 10px;
    }
  }
}
</style>
